package cn.web.base.controller;

import cn.commons.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

	protected HttpServletRequest request;


	public HttpServletRequest getServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	protected HttpServletRequest getRequest() {
		this.request = getServletRequest();
		return this.getServletRequest();
	}

	protected HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		if (session == null) {
			session = getRequest().getSession();
		}
		return session;
	}

	protected ServletContext getServletContext() {
		return getSession().getServletContext();
	}

	public static Map<String, Object> getRequestMap(HttpServletRequest request) {
		return putMapValue(request, false);
	}

	public static Map<String, Object> getRequestMapNotNull(HttpServletRequest request) {
		return putMapValue(request, true);
	}


	private static Map<String, Object> putMapValue(HttpServletRequest request, boolean isHandlerNull) {
		Enumeration<String> enumerations = request.getParameterNames();
		Map params = new HashMap();
		while (enumerations.hasMoreElements()) {
			String _key = enumerations.nextElement();
			String value = request.getParameter(_key);
			if (isHandlerNull && StringUtils.isNotBlank(value)) {
				if (StringUtils.isNull(value)) {
					value = null;
				}
			}
			params.put(_key, value);

		}
		return params;
	}
}
